import { Provide, Singleton } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BillCodeInfo } from '../entity/BillCodeInfo.entity';
@Provide('BillCodeGenerator')
@Singleton()
export class BillCodeGenerator {
  @InjectEntityModel(BillCodeInfo)
  billCodeInfoRepo: Repository<BillCodeInfo>;
  async nextCode(prefix: string): Promise<string> {
    const billCodeInfo = await this.billCodeInfoRepo.findOneBy({
      prefix,
    });
    console.log('试图查询： ', prefix, billCodeInfo);
    let resultNumber = 0;
    if (!billCodeInfo) {
      // 第一次获取
      resultNumber = 1;
      const bc = new BillCodeInfo();
      bc.current = resultNumber + 1;
      bc.prefix = prefix;
      bc.id = 0;
      await this.billCodeInfoRepo.save(bc);
    } else {
      // 第n此获取
      // console.log('第n此获取');
      resultNumber = billCodeInfo.current;
      billCodeInfo.current++;
      await this.billCodeInfoRepo.save(billCodeInfo);
    }
    console.log('成功拿到流水号核心', prefix, resultNumber);
    const head = prefix;
    const body = new Date().getTime();
    const foot = String(resultNumber).padStart(4, '0');
    return head + body + foot;
  }
}
